package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("AdditiveaddressService")
@Transactional

public class AdditiveaddressServiceImpl extends CmiEmaService implements AdditiveaddressService {
	public AdditiveaddressServiceImpl() {
	}

	@Transactional
	public Additiveaddress saveAdditiveaddress(Additiveaddress additiveaddress) {

		if (additiveaddress.getId() == null) {
			Additive additive = additiveDAO.findAdditiveById(additiveaddress.getAdditive().getId());
			Address address = addressDAO.findAddressById(additiveaddress.getAddress().getId());
			Unit unit = unitDAO.findUnitById(additiveaddress.getUnit().getId());

			Additiveaddress existingAdditiveaddress = additiveaddressDAO.findAdditiveaddressByPhysicalPrimaryKey(
					additive.getId(), address.getId(), additiveaddress.getTime());

			additiveaddress.setAdditive(additive);
			additiveaddress.setAddress(address);
			additiveaddress.setUnit(unit);

			if (isEquals(additiveaddress, existingAdditiveaddress)) {
				return existingAdditiveaddress;
			}

			additiveaddress = additiveaddressDAO.store(additiveaddress);
			additiveaddressDAO.flush();

		} else {
			Additiveaddress existingAdditiveaddress = additiveaddressDAO
					.findAdditiveaddressByPrimaryKey(additiveaddress.getId());

			additiveaddress = additiveaddressDAO.store(additiveaddress);
			additiveaddressDAO.flush();
		}

		return additiveaddress;
	}

	public void deleteAdditiveaddress(Additiveaddress additiveaddress) {
		additiveaddressDAO.remove(additiveaddress);
		additiveaddressDAO.flush();
	}

	@Transactional
	public void deleteAdditiveaddresss(Set<Integer> deleteAdditiveaddresssId) {
		Query query = additiveaddressDAO.createNamedQuery("deleteAdditiveaddresssById", -1, -1);
		query.setParameter(1, deleteAdditiveaddresssId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Additiveaddress> loadAdditiveaddresss() {
		return additiveaddressDAO.findAllAdditiveaddresss();

	}

	@Transactional
	public Set<Additiveaddress> loadReferenceAdditiveaddresss(Set<Additiveaddress> additiveaddresss) {
		Iterator<Additiveaddress> additiveaddresssIterator = additiveaddresss.iterator();
		Set<Additiveaddress> referencedAdditiveaddresss = new HashSet<>();
		while (additiveaddresssIterator.hasNext()) {
			Additiveaddress currentAdditiveaddress = additiveaddresssIterator.next();

		}
		return referencedAdditiveaddresss;
	}

	public Set<Additiveaddress> loadAdditiveaddresssByIdSet(Set<Integer> additiveaddressIdSet) {

		Iterator<Integer> additiveaddressIdIterator = additiveaddressIdSet.iterator();
		Set<Additiveaddress> additiveaddressSet = new HashSet<>();
		while (additiveaddressIdIterator.hasNext()) {
			Integer id = additiveaddressIdIterator.next();
			Additiveaddress currentAdditiveaddress = additiveaddressDAO.findAdditiveaddressById(id);
			additiveaddressSet.add(currentAdditiveaddress);
		}
		return additiveaddressSet;
	}

	@Transactional
	public List<Additiveaddress> findAllAdditiveaddresss(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Additiveaddress>(
				additiveaddressDAO.findAllAdditiveaddresss(startResult, maxRows));
	}

	@Transactional
	public Additiveaddress findAdditiveaddressByPrimaryKey(Integer id) {
		return additiveaddressDAO.findAdditiveaddressByPrimaryKey(id);
	}

	@Transactional
	public Integer countAdditiveaddresss() {
		return ((Long) additiveaddressDAO.createQuerySingleResult("select count(o) from Additiveaddress o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countAdditiveaddresss(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Additiveaddress.class);
		return ((Long) additiveaddressDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countAdditiveaddresssByName(String queryName) {
		Query query = additiveaddressDAO.createNamedQuery("countAdditiveaddresssByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countAdditiveaddresssByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Additiveaddress.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadAdditiveaddressObjectReferencedSet(Additiveaddress additiveaddress) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (additiveaddress.getAdditive() != null) {

			Set<Integer> additiveIds = new HashSet<Integer>();
			additiveIds.add(additiveaddress.getAdditive().getId());
			objectReferencedSetMap.put("additiveIds", additiveIds);
		}
		if (additiveaddress.getAddress() != null) {

			Set<Integer> addressIds = new HashSet<Integer>();
			addressIds.add(additiveaddress.getAddress().getId());
			objectReferencedSetMap.put("addressIds", addressIds);
		}
		if (additiveaddress.getUnit() != null) {

			Set<Integer> unitIds = new HashSet<Integer>();
			unitIds.add(additiveaddress.getUnit().getId());
			objectReferencedSetMap.put("unitIds", unitIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadAdditiveaddressClassReferencedSet(Additiveaddress additiveaddress) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("additives", additiveDAO.findAllAdditives());
		classReferencedSetMap.put("addresss", addressDAO.findAllAddresss());
		classReferencedSetMap.put("units", unitDAO.findAllUnits());

		return classReferencedSetMap;
	}

	public boolean isEquals(Additiveaddress additiveaddress, Object obj) {
		if (obj == additiveaddress)
			return true;
		if (!(obj instanceof Additiveaddress))
			return false;
		Additiveaddress comparedAdditiveaddress = (Additiveaddress) obj;
		if (!CheckPropertyEqual(additiveaddress.getAdditive().getId(), comparedAdditiveaddress.getAdditive().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(additiveaddress.getAddress().getId(), comparedAdditiveaddress.getAddress().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(additiveaddress.getTime(), comparedAdditiveaddress.getTime())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

